"""
多线程对共享数据的并发访问导致了数据的不一致，因此当涉及到共享数据的修改的时候，需要锁
"""
import threading
from threading import Thread, Lock
import os, time

a = 50
lock = Lock()


def buy():
    global a
    for i in range(1, 101):
        lock.acquire()
        if a > 0:
            a -= 1
            print(f"{threading.current_thread().name}a的值为%d" % a)
            lock.release()
        time.sleep(1)


if __name__ == '__main__':
    print("-----主进程开始-------")
    for i in range(3):
        p = Thread(target=buy)
        p.start()
    for i in range(3):
        p.join()

    print(a)
    print("-----主进程结束-------")
